<template>
  <el-drawer
    class="draw-style"
    :title="title"
    :visible.sync="open"
    direction="rtl"
    size="42%"
    :wrapperClosable="false"
    :destroy-on-close="false"
    :before-close="cancel">
    <div class="draw-container">
      <!-- 学习配置 -->
      <div style="display: flex; margin-top: 30px; margin-bottom: 30px">
        <div class="line" />
        <div class="title">学习配置</div>
      </div>
      <!-- 表单 -->
      <el-form ref="formRef" :model="formData" label-width="100px" class="demo-ruleForm" style="margin-left: 8px">
        <el-row>
          <el-col :span="24">
            <el-form-item prop="type" label="执行方式">
              <el-radio-group v-model="formData.type" size="small" @change="changeRadio">
                <el-radio border label="fixRate">周期性执行</el-radio>
                <el-radio border label="timing">定时执行</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- 周期执行 -->
          <el-col :span="24">
            <el-form-item
              prop="type"
              label="执行配置"
              :rules="{
                required: true,
                message: '不能为空 ',
              }">
              <div v-if="formData.type == 'timing'">
                每
                <el-select
                  v-model="formData.timing.lifecycle"
                  placeholder="请选择"
                  clearable
                  style="width: 150px; margin: 0 10px">
                  <el-option label="天" value="day" />
                </el-select>
                <el-time-select
                  v-model="formData.tempTime"
                  placeholder="请选择"
                  clearable
                  style="width: 150px; margin-right: 20px"
                  :picker-options="{
                    start: '00:00',
                    step: '01:00',
                    end: '23:00',
                  }" />
                执行一次
              </div>
              <div v-else :span="24">
                每
                <!-- 小时时 -->
                <el-select
                  v-if="formData.fixRate.unit == 'hour'"
                  v-model="formData.fixRate.frequency"
                  placeholder="请选择"
                  clearable
                  :disabled="!formData.fixRate.unit"
                  style="width: 150px; margin: 0 10px">
                  <el-option v-for="(item, index) in 24" :key="index" :label="item" :value="item" />
                </el-select>
                <!-- 分钟时 -->
                <el-select
                  v-else
                  v-model="formData.fixRate.frequency"
                  placeholder="请选择"
                  clearable
                  :disabled="!formData.fixRate.unit"
                  style="width: 150px; margin: 0 10px">
                  <el-option v-for="(item, index) in 60" :key="item + '' + index" :label="item" :value="item" />
                </el-select>
                <!-- 选择小时还是分钟 -->
                <el-select
                  v-model="formData.fixRate.unit"
                  placeholder="请选择"
                  clearable
                  style="width: 150px; margin-right: 20px">
                  <el-option label="分钟" value="min" />
                  <el-option label="小时" value="hour" />
                </el-select>
                执行一次
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="model == 'whitelist'">
          <el-form-item
            label="重合度阈值"
            prop="cond"
            :rules="{
              required: true,
              message: '不能为空 ',
            }">
            <!-- <el-input v-model="formData.cond"  placeholder="请输入重合度阈值" maxlength="50" /> -->
            <el-input-number v-model="formData.cond" :rules="{
                required: true,
                message: '不能为空 ',
              }" style="width: 340px" :min="0.1" :precision="2" :step="0.1" :max="1" label="请输入重合度阈值"></el-input-number>
          </el-form-item>
          <el-form-item
            label="比例阈值"
            prop="t"
            :rules="{
              required: true,
              message: '不能为空 ',
            }">
            <!-- <el-input v-model="formData.t" style="width: 460px" placeholder="请输入比例阈值" maxlength="50" /> -->
            <el-input-number v-model="formData.t" style="width: 340px" :min="0.1" :precision="2" :step="0.1" :max="1" label="请输入比例阈值"></el-input-number>
          </el-form-item>
        </template>
      </el-form>
      <!-- 基线配置 -->
      <div style="display: flex; margin-top: 30px; margin-bottom: 15px">
        <div class="line" />
        <div class="title">基线配置</div>
      </div>
      <!-- 数值默认值 -->
      <!-- 表单 -->
      <el-form
        ref="formRef"
        :model="formData"
        label-width="100px"
        class="demo-ruleForm"
        style="margin-left: 8px">
        <!--  prop="threshold" -->
        <el-form-item
          label="默认值"
          v-if="model == 'threshold'"
          >
           <el-input-number v-model="formData.threshold" :precision="2" :step="0.1" :min="1" :max="9999"></el-input-number>
          <!-- <el-button type="text" style="margin-left: 10px" @click="handleDel('threshold')">清除</el-button> -->
        </el-form-item>
<!--  prop="timeRange" -->
        <el-form-item
          label="默认值"
          v-else-if="model == 'time_range'"
          >
          <el-time-picker
            v-model="formData.timeRange"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            value-format="hh:mm:ss"
            style="width: 460px" />
          <!-- <el-button type="text" style="margin-left: 10px" @click="handleDel('time_range')">清除</el-button> -->
        </el-form-item>
      </el-form>
      <!-- 范围默认值 -->
      <!-- 表格 -->
      <div class="col-right" v-if="model == 'whitelist'">
        <!-- 表格 -->
        <div style="font-size: 14px; color: #606266; margin-left: 10px">默认列表</div>
        <el-form ref='formRef' :model="formData" label-width="0px">
          <hk-table
            :table-columns="tableTitle"
            :table-data="formData.whitelists"
            :show-index="true"
            :total="total"
            :show-pag="false"
            :isNeedIndex='true'
            :operate="true"
            :query-params="queryParams"
            :table-height="60"
            >
            <!-- 状态 -->
            <template #operate="scope">
              <el-button type="text" @click="handleDetail(scope.row)">删除</el-button>
            </template>
            <!-- 默认值 -->
            <template #count="scope">
              <!--  :prop="'whitelists.' + scope.row.$index + '.count'" -->
              <el-form-item
              label=""
              >
              <el-input  v-model="scope.row.row.count" placeholder="请输入" maxlength="50" />
              </el-form-item>
            </template>
          </hk-table>
        </el-form>
        <el-button style="border: 1px dashed #2979ff; width: 100%" icon="el-icon-plus" @click="handleAddRow"
          >新增一行</el-button
        >
      </div>
    </div>
    <div class="draw-footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-drawer>
</template>
<script>
import HkTable from '@/components/Hk-Table'
// import monthlyOptions from '@/mock/mockData/prodtctType.json'
import { getDictList } from '@/api/milkyway/jobScheduling'
import { settings, addThresholdsDefault, addTimeRangesDefault, addWhitelistsDefault,delThresholdsDefault,delTimeRangesDefault,delWhitelistsDefault } from '@/api/icp/baseline.js'

// import HKSearchform from '@/components/HkSearchform'
export default {
  components: { HkTable },
  props: {
    title: {
      type: String,
      default() {
        return '配置'
      },
    },
  },
  data() {
    return {
      // 是否显示弹出层
      open: false,
      // 标题宽度
      labelWidth: '120',
      // 是否显示按钮
      btnHidden: true,
      // 表单项配置
      formData: {
        type: 'fixRate',
        fixRate: {},
        timing: {},
        whitelists: [],
        cond: 0.7,
        t: 0.9,
      },
      studyList: [
        { label: '近一周', value: '1' },
        { label: '近一月', value: '2' },
        { label: '近一年', value: '3' },
      ],
      // 搜索框
      searchData: {},
      fieldList: [
        {
          label: '',
          type: 'input',
          field: 'name',
          placeholder: '请输入基线名称',
          width: '20px',
          maxlength: 20,
        },
        {
          label: '',
          type: 'select',
          field: 'status',
          placeholder: '任务状态',
          maxlength: 20,
          list: 'deptList',
        },
      ],
      dictList: {
        deptList: [
          { label: '启用', value: '1' },
          { label: '停用', value: '2' },
        ],
      },
      // 表格
      tableTitle: [
        // { label: '基线名称', param: 'name' },
        // { label: '任务状态', param: 'status', type: 'slot' },
        { label: '默认值', param: 'count', type: 'slot' },
      ],
      tableList: [
        {
          name: '打印文件数量基线',
          status: 0,
        },
      ],
      queryParams: {
        current: 1,
        size: 10,
      },
      loading: false,
      // 选中的id值们
      ids: [],
      // 分页总条数
      total: 0,
      // value1: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
      type: null,
      model: null,
    }
  },

  mounted() {
    // this.getConfigureObj()
  },
  methods: {
    /**
     * @params  type  
     * @params  type  
     * @params  params    学习配置数据的回显值
     * @params  defaultData  默认值与重合度阈值、比例阈值回显值
     */
    show(type, model,params,defaultData) {
      this.type = type
      this.model = model
      this.formData.type=params.type
      if(params.type=="fixRate"){
        this.formData.fixRate={
          frequency:params.fixRate.frequency,
          unit:params.fixRate.unit
        }
      }else{
        this.formData.timing.lifecycle=params.timing.lifecycle
        let tempTime=(params.timing.hour>10?params.timing.hour:'0'+params.timing.hour)+':00' 
        this.$set(this.formData,'tempTime',tempTime)
      }
      this.open = true;
    switch(model){
      case 'threshold':
          this.$set(this.formData,'threshold',defaultData.threshold)
        break;
      case 'time_range':
        this.$set(this.formData,'timeRange',[defaultData.startTime,defaultData.endTime])
      break;
      case 'whitelist':
        let whitelists=[]
        if(defaultData.params){
          this.$set(this.formData,'cond',defaultData.params.cond)
          this.$set(this.formData,'t',defaultData.params.t)
        }
        if(defaultData.defatleTableList && defaultData.defatleTableList.length>0){
          whitelists=defaultData.defatleTableList.map(i=>({count:i}))
          this.$set(this.formData,'whitelists',whitelists)
        }
      break;
    }
      
    },
    // 选择执行方式
    changeRadio(val) {
      if (val === 'fixRate') {
        this.$message('请先选择【分钟/小时】，再选择【数值】')
        this.formData.timing = {}
      } else {
        this.formData.fixRate = {}
      }
    },

    /** 作业类型改变事件 */
    handleChange(value, type) {
      this.formData[type] = value.toString()
    },

    //   新增一行
    handleAddRow() {
      let obj = { count: '' }
      this.formData.whitelists.push(obj)
    },
    // 删除行
    handleDetail(row) {
      this.formData.whitelists.splice(row.$index, 1)
    },
    /** 提交按钮 */
    submitForm() {
      //  1.判断执行配置并处理数据
      if (
        (this.formData.tempTime && this.formData.timing.lifecycle) ||
        (this.formData.fixRate.frequency && this.formData.fixRate.unit)
      ) {
        // 当选择定时执行时
        if (this.formData.tempTime) {
          this.formData.timing.hour = Number(this.formData.tempTime.split(':')[0])
          this.formData.timing.time=Number(this.formData.tempTime.split(':')[1])
        }
        // 处理描述
        if (this.formData.type === 'fixRate') {
          this.formData.desc = `每${this.formData.fixRate.frequency}${
            this.formData.fixRate.unit === 'hour' ? '小时' : '分钟'
          }执行一次`
        } else {
          this.formData.desc = `每天${this.formData.timing.hour}点执行一次`
        }
      } else {
        this.$message.warning('请完善执行配置')
        return false
      }
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          //  提交学习配置信息
          let settingsRes = await settings(this.type, {
            cronObject: {
              timing: this.formData.timing,
              type: this.formData.type,
              desc: this.formData.desc,
              fixRate: this.formData.fixRate,
            },
            params: {
                cond: this.model == 'whitelist' ? this.formData.cond : null,
                t: this.model == 'whitelist' ? this.formData.t : null,
              },
          })
          if (settingsRes) {
            let res = null
            switch (this.model) {
              case 'threshold':
                res =await addThresholdsDefault(this.type, { threshold: this.formData.threshold })
                break
              case 'time_range':
                  res =await addTimeRangesDefault(this.type, {
                  startTime:this.formData.timeRange?this.formData.timeRange[0]:null,
                  endTime: this.formData.timeRange?this.formData.timeRange[1]:null,
                })
                break
              case 'whitelist':
                let hasData=this.formData.whitelists.every(i=>{
                  return i.count && i.count!=''
                });
                if(!hasData){
                  this.$message.error('基线配置中的默认列表值不能为空，请填写或删除！')
                  return false;
                }
                let whitelists = this.formData.whitelists.map((i) => i.count)
                res =await addWhitelistsDefault(this.type, { whitelists: whitelists })
                break
            }
            if (res==true || res=='successful') {
              this.$message.success('保存成功');
              this.cancel();
              this.$emit('handleSubmit')
            }
          }
          return
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.formData = {
        fixRate: {},
        timing: {},
        whitelists: [],
        type: 'fixRate',
        cond: 0.7,
        t: 0.9,
      }
      this.$refs.formRef.resetFields()
    },
    //  删除阈值或时间范围类基线
    handleDel(type){
      switch(type){
        case 'threshold':
          this.formData.threshold=null;
        delThresholdsDefault(this.type).then(res=>{
          this.$message.success("清除成功")
        })
        break;
        case 'time_range':
           this.formData.timeRange=null;
          delTimeRangesDefault(this.type).then(res=>{
          this.$message.success("清除成功")
        })
        break;
      }
    }
  },
}
</script>

<style scoped lang="scss">
.targetTable .el-form-item{
margin-bottom:0px !important;
}
::v-deep .el-table__body-wrapper {
  height: auto !important;
}
.el-radio.is-bordered {
  border: 0px;
}
.son-panel {
  display: flex;
}
.draw-container {
  flex: 1;
  overflow: auto;
  .title{
    font-size: 14px; color: #2f343e; font-weight: 600
  }
}
.draw-footer {
  text-align: right;
  padding: 0 20px;
}
.line {
  width: 2px;
  height: 14px;
  background: #4b6eef;
  margin-right: 8px;
}
.col-right {
  //   padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}
.draw-style {
  ::v-deep {
    .el-drawer__body {
      padding: 20px 0px;
      padding-top: 0px;
    }
  }
}
.draw-container {
  padding: 20px;
}
::v-deep {
  .el-form-item__label {
    text-align: left;
  }
}
</style>
